from django.shortcuts import render
from django.views import View
from apps.verifications.libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django import http
import logging
from celery_tasks.sendmessage.tasks import ccp_send_message
# from apps.verifications.yuntongxun.ccp_sms import CCP
# Create your views here.
logger = logging.getLogger('django')
class ImagecodeView(View):
    def get(self,request,uuid):
        '''
         生成图形验证码, 保存到redis中, 另外返回图片
        :param
        request: 请求对象
        :param
        uuid: 浏览器端生成的唯一id
        :return:一个图片
        '''

        # 1.调用工具类 captcha 生成图形验证码
        text, image = captcha.generate_captcha()

        # 保存到redis2号库
        redis_conn = get_redis_connection('verify_code')

        # 保存图片验证码
        print(uuid)
        redis_conn.setex('image_%s'%uuid,360,text)

        # 打错了 HttpResponse
        # return http.response(image,
        #                     content_type='image/jpg')

        return http.HttpResponse(image, content_type='image/jpg')


class MessageSendView(View):
    def get(self,request,mobile):
        """
          :param reqeust: 请求对象
          :param mobile: 手机号
          :return: JSON
          """

        # 1.接收参数
        # mobile 是用路径传递参数的
        # image_code 和 image_code_id 是用查询字符串传递的参数.

        redis_conn = get_redis_connection('verify_code')
        # 向数据库访问是否有标记
        # a=redis_conn.get('flag_%s' % mobile)
        if redis_conn.get('flag_%s' % mobile):
            return http.JsonResponse({'code':400,'errmsg':'请求频繁'})

        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')

        # 2. 校验参数是否完整
        if not all([image_code,uuid]):
            return http.JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        # 3.向redis数据库取出图片验证码和uuid
        # redis_conn = get_redis_connection('verify_code')
        # redis取到的数据是byte类型
        img = redis_conn.get('image_%s'%uuid)
        if not img:
            return http.JsonResponse({'code':400,'errmsg':'提取图片验证码失败'})

        # 4.取到后删除
        try:
            redis_conn.delete('image_%s'%uuid)

        except Exception as e:
            logger(e)

        # 5.对比前端传进的和后端数据库取到的是否一致
        img_str = img.decode()
        # if img_str.lower() != uuid.lower(): 取错对象了
        if img_str.lower() != image_code.lower():
            print('不相等')
            return http.JsonResponse({'code':400,'errmsg':'验证码不相等'})

        # 6.生成短信验证码
        sms_code = 'jojo'

        # 7.保存短信验证码
        # redis_conn.setex('sms_%s'%mobile,360,sms_code)

        # 8.发送验证码,类().方法
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)

        # 管道
        p1 =  redis_conn.pipeline()

        p1.setex('sms_%s'%mobile,360,sms_code)

        print(sms_code, '验证码，假装已经发送')

        p1.setex('flag_%s' % mobile, 10, 100)

        p1.execute()



        ccp_send_message.delay(mobile,sms_code)
        print('ok')

        return http.JsonResponse({'code': 0,
                                  'errmsg': '发送短信成功'})






